import { addUser, apiInterceptors, getRoleList, setUserRole, getUserRoleList } from '@/client/api';
import { CreateUserParams } from '@/types/user';
import { useRequest } from 'ahooks';
import { App, Form, Input, Modal, Spin , Radio } from 'antd';
import React, { useMemo , useEffect, useState} from 'react';
import { useTranslation } from 'react-i18next';
import { useRouter } from 'next/router';
import styles from './styles.module.css';

interface AssigningRolesProps {
  open: boolean;
  onCancel: () => void;
  refresh?: () => Promise<void>;
}

const AssigningRoles: React.FC<AssigningRolesProps> = ({ 
  open, 
  onCancel, 
  refresh 
}) => {
  const { t } = useTranslation();
  const { message } = App.useApp();
  const [form] = Form.useForm();
  const userInfo = {
    ...{user_role:2}, // 使用默认值
    ...JSON.parse(localStorage.getItem('edit_user_info') || '{}'),
  };
  const [dataSource, setDataSource] = useState<any>([]);

  const formItems = useMemo(() => [
    {
      name: 'login_name',
      label: t('user_name'),
      rules: [{ required: true, message: t('user_name_required')}],
      required:true,
    },
    {
      name: 'nick_name',
      label: t('user_nickname'),
      rules: [{required: true, message: t('user_nickname_required')},],
      required:true,
    },
  ], [t]);

  const { run: setRole, loading: isSubmitting } = useRequest(
      async (params: any) => {
        const [error] = await apiInterceptors(setUserRole({user_id:userInfo.id,role_id:params.user_role}));
        if (error) throw error;
        return params;
      },
      {
        manual: true,
        onSuccess: async (data) => {
          message.success(t('update_success'));
          await refresh?.();
          onCancel();
        },
        onError: () => {
          message.error(t('update_failed'));
        },
      }
    );
    
    const { run: initData } = useRequest(
      async () => {
        return await apiInterceptors(getRoleList({}));
      },
      {
        manual: true,
        onSuccess: (res: any) => {
          if (res[2] && res[2].success && Array.isArray(res[2].data)) {
            let list = res[2].data.map((item:any)=>{
              return {value:item.id,label:item.name}
            })
            return setDataSource(list)
          }
        },
      },
    );

    const { run: getAllList } = useRequest(
      async () => {
        return await apiInterceptors(getUserRoleList({user_id:userInfo.id}));
      },
      {
        manual: true,
        onSuccess: (res: any) => {
          let newUserInfo = {...userInfo,user_role: 2}
          if (res[2] && res[2].success && res[2].data.id) {
            newUserInfo.user_role = res[2].data.id
          }
          localStorage.setItem('edit_user_info', JSON.stringify(newUserInfo));
          form.setFieldsValue({ user_role: newUserInfo.user_role }); 
        },
      },
    );
  
    useEffect(() => {
      initData();
      getAllList();
    }, []);
  

  return (
    <Modal
      className={styles['modal-container']}
      title={t('assigning_roles')}
      width={800}
      open={open}
      okButtonProps={{ disabled: isSubmitting }}
      onOk={async () => {
        try {
          const values = await form.validateFields();
          await setRole(values);
        } catch (error) {
          console.error('Submission error:', error);
        }
      }}
      onCancel={onCancel}
      centered
    >
      <Spin spinning={isSubmitting}>
        <Form form={form} initialValues={userInfo} labelAlign="right" className='w-4/5'>
          {formItems.map(({ name, label, rules }) => (
            <Form.Item required labelCol={{ span: 8 }} wrapperCol={{ span: 16 }} key={name} name={name} label={label} rules={rules}>
              <Input maxLength={30} disabled placeholder={label} autoComplete="off" />
            </Form.Item>
          ))}
          <Form.Item
            labelCol={{ span: 8 }} 
            wrapperCol={{ span: 16 }} 
            label={`${t('user_role')}：`}
            name='user_role'
            required
            rules={[{ required: true, message: t('user_role_required') }]}
          >
            <Radio.Group
              options={dataSource}
            />
          </Form.Item>
        </Form>
      </Spin>
    </Modal>
  );
};

export default AssigningRoles;